package org.znxs.comfriend.adapters;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.google.android.material.card.MaterialCardView;

import org.znxs.comfriend.R;
import org.znxs.comfriend.activities.FriendDetailActivity;
import org.znxs.comfriend.models.User;
import org.znxs.comfriend.utils.FollowManager;
import org.znxs.comfriend.utils.LoginUser;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

public class FriendCardAdapter extends RecyclerView.Adapter<FriendCardAdapter.FriendCardViewHolder> {
    private Context context;
    private List<User> users;

    private FollowManager followStance;

    private LoginUser loginUser = LoginUser.getInstance(context);

    public FriendCardAdapter(Context context, List<User> users) {
        this.context = context;
        this.users = new ArrayList<>(users); // 使用新的列表实例来避免潜在的问题
        this.followStance = FollowManager.getInstance(context);

    }

    @NonNull
    @Override
    public FriendCardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_feed_card, parent, false);
        return new FriendCardViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull FriendCardViewHolder holder, int position) {
        User user = users.get(position);

        // 设置用户信息
        holder.tvUsername.setText(user.getNickname());
        holder.tvBio.setText(user.getBio());

        // 使用 Glide 加载头像
        String avatarUrl = user.getAvatarUrl();
        if (avatarUrl != null && !avatarUrl.isEmpty()) {
            Glide.with(context).load(avatarUrl).placeholder(R.drawable.pengyiyan).error(R.drawable.error).into(holder.ivAvatar);
        } else {
            holder.ivAvatar.setImageResource(R.drawable.pengyiyan);
        }

        // 获取图片路径列表
        List<String> imagePaths = user.getImages();

        // 如果没有图片，隐藏所有 ImageView
        if (imagePaths == null || imagePaths.isEmpty()) {
            for (ImageView imageView : holder.imageViews) {
                if (imageView != null) { // 防止空指针异常
                    imageView.setVisibility(View.GONE);
                }
            }
            return;
        }

        // 显示图片，最多显示 3 张
        for (int i = 0; i < holder.imageViews.length; i++) {
            if (i < imagePaths.size()) {
                // 显示图片
                holder.imageViews[i].setVisibility(View.VISIBLE);
                Glide.with(context).load(imagePaths.get(i)).placeholder(R.drawable.pengyiyan).error(R.drawable.error).into(holder.imageViews[i]);
            } else {
                // 隐藏多余的 ImageView
                if (holder.imageViews[i] != null) { // 防止空指针异常
                    holder.imageViews[i].setVisibility(View.GONE);
                }
            }
        }

        // 设置初始关注按钮的状态
        updateFollowButton(holder.btnFollow, user.getId());

        // 设置点击事件
        holder.btnFollow.setOnClickListener(v -> {
            String userId = user.getId();

            if(loginUser.getLoginUser()!=null){
                if (followStance.isFollowing(userId)) {
                    // 如果已关注，则取消关注
                    followStance.removeItem(userId);
                    Toast.makeText(context, "已取消关注: " + user.getNickname(), Toast.LENGTH_SHORT).show();
                    // 更新按钮状态
                    updateFollowButton(holder.btnFollow, userId);
                } else {
                    // 如果未关注，则关注
                    followStance.addItem(userId);
                    Toast.makeText(context, "已关注: " + user.getNickname(), Toast.LENGTH_SHORT).show();
                    // 更新按钮状态
                    updateFollowButton(holder.btnFollow, userId);
                }
            }else {
                Toast.makeText(context, "未登录,请登录后再操作",Toast.LENGTH_SHORT).show();
            }




        });

        // 设置点击监听器：进入详情页
        holder.cardView.setOnClickListener(v -> {
            Intent intent = new Intent(context, FriendDetailActivity.class);
            intent.putExtra("user", user);
            context.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        return users.size();
    }

    /**
     * 更新适配器中的数据并刷新 RecyclerView
     */
    public void updateData(List<User> newData) {
        Log.d("FriendCardAdapter", "Updating data with size: " + newData.size());
        this.users.clear(); // 清空旧数据
        this.users.addAll(newData); // 添加新数据
        notifyDataSetChanged(); // 刷新 RecyclerView
    }

    /**
     * 更新关注按钮的状态
     */
    // 根据是否初始化和关注状态更新按钮
    private void updateFollowButton(Button btnFollow, String userId) {
        // 判断是否已关注
        boolean isFollowing = followStance.isFollowing(userId);

        // 设置按钮文本和样式
        if (isFollowing) {
            setButtonStyle(btnFollow, "已关注", android.R.color.black, R.color.Following, context);
        } else {
            setButtonStyle(btnFollow, "关注", android.R.color.white, R.color.Follow, context);
        }
    }

    // 设置按钮样式的方法
    private void setButtonStyle(Button button, String text, int textColorRes, int backgroundColorRes, Context context) {
        button.setText(text);
        button.setTextColor(context.getResources().getColor(textColorRes));
        button.setBackgroundColor(context.getResources().getColor(backgroundColorRes));
    }

    /**
     * 更新指定用户的关注状态
     */
    public void updateUserFollowStatus(String userId, boolean isFollowing) {
        for (User user : users) {
            if (user.getId().equals(userId)) {
                int position = users.indexOf(user);
                notifyItemChanged(position);
                break;
            }
        }
    }

    static class FriendCardViewHolder extends RecyclerView.ViewHolder {
        MaterialCardView cardView; // 卡片视图
        CircleImageView ivAvatar;  // 用户头像
        TextView tvUsername, tvBio; // 用户名和简介
        ImageView[] imageViews;     // 图片数组，用于显示最多 3 张图片
        Button btnFollow;           // 关注按钮

        FriendCardViewHolder(View itemView) {
            super(itemView);
            cardView = itemView.findViewById(R.id.card_view); // 绑定卡片视图
            ivAvatar = itemView.findViewById(R.id.iv_avatar); // 绑定头像
            tvUsername = itemView.findViewById(R.id.tv_username); // 绑定用户名
            tvBio = itemView.findViewById(R.id.tv_bio); // 绑定简介
            btnFollow = itemView.findViewById(R.id.btn_follow); // 绑定关注按钮

            // 初始化 ImageView 数组
            imageViews = new ImageView[]{itemView.findViewById(R.id.iv_image_1), itemView.findViewById(R.id.iv_image_2), itemView.findViewById(R.id.iv_image_3),};
        }
    }

}
